<?php

namespace Aoe\Emulator\Schema\Element;

use Aoe\Emulator\Ifc\Key;
use Aoe\Emulator\Ifc\Type;

/**
 * # 选项列表
 */
class Options
{
    public function __construct(protected array $options)
    {
        $items   = [];
        $labels = [];
        $values = [];
        foreach ($options as $key => $value) {
            $_                   = self::make_pair($value, $key);
            $labels[$_[Key::VALUE]] = $_[Key::LABEL];
            $values[$_[Key::LABEL]] = $_[Key::VALUE];
            $items[]                 = $_;
        }

        $this->items  = $items;
        $this->labels = $labels;
        $this->values = $values;
    }

    /**
     * @var array<array{ label: string, value: string | int }>
     */
    private(set) array $items {
        get {
            return $this->items;
        }
    }

    /**
     * @var ?array<string> value => label
     */
    private(set) ?array $labels {
        get {
            return $this->labels;
        }
    }

    /**
     * @var ?array<int>|array<string> label => value
     */
    private(set) ?array $values {
        get {
            return $this->values;
        }
    }

    private static function make_pair($v, $k): array
    {
        if (is_array($v)) return [
            Key::VALUE => $v[Key::VALUE] ?? $v[Type::ID] ?? null,
            Key::LABEL => $v[Key::LABEL] ?? $v[Key::NAME] ?? null,
        ];

        if (is_numeric($k)) return [Key::VALUE => $k, Key::LABEL => $v];

        return [Key::VALUE => $v, Key::LABEL => $k];
    }

    /**
     * @noinspection PhpUnused
     */
    public function getLabel(int $value): string
    {
        return $this->labels[$value] ?? '';
    }

    public function getValue(string $label): int
    {
        return $this->values[$label] ?? 0;
    }
}